﻿namespace CSharpPro._1106;

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class IUserServiceImpl : IUserService
{
    private readonly List<User> _users = new List<User>();

    public void ShowMainMenu()
    {
        while (true)
        {
            Console.Clear();
            Console.WriteLine("===== 用户认证系统 =====");
            Console.WriteLine("1. 登录");
            Console.WriteLine("2. 注册");
            Console.WriteLine("3. 退出");
            Console.Write("\n请选择功能（1-3）：");

            string input = Console.ReadLine()?.Trim();
            if (!int.TryParse(input, out int choice))
            {
                Console.WriteLine("请输入有效数字（1-3）！");
                Pause();
                continue;
            }

            switch (choice)
            {
                case 1:
                    UserLogin();
                    break;
                case 2:
                    UserRegister();
                    break;
                case 3:
                    Console.WriteLine("系统已退出，感谢使用！");
                    return;
                default:
                    Console.WriteLine("请输入1-3之间的数字！");
                    Pause();
                    break;
            }
        }
    }

    public bool Register(string username, string password)
    {
        if (_users.Exists(u => u.Username == username))
        {
            return false;
        }
        
        _users.Add(new User(username, password));
        return true;
    }

    public bool Login(string username, string password)
    {
        return _users.Exists(u => u.Username == username && u.Password == password);
    }

    public void UserRegister()
    {
        Console.Clear();
        Console.WriteLine("===== 用户注册 =====");

        string username;
        while (true)
        {
            Console.Write("请输入用户名：");
            username = Console.ReadLine()?.Trim();

            if (string.IsNullOrEmpty(username))
            {
                Console.WriteLine("用户名不可为空！");
                continue;
            }

            if (username.Length < 3 || username.Length > 15)
            {
                Console.WriteLine("用户名长度必须为3-15个字符！");
                continue;
            }

            if (!Regex.IsMatch(username, @"^[a-zA-Z0-9_]+$"))
            {
                Console.WriteLine("用户名只能包含字母、数字和下划线！");
                continue;
            }

            if (_users.Exists(u => u.Username == username))
            {
                Console.WriteLine("该用户名已被注册，请更换！");
                continue;
            }

            break;
        }

        string password;
        while (true)
        {
            Console.Write("请输入密码：");
            password = ReadPassword();

            if (string.IsNullOrEmpty(password))
            {
                Console.WriteLine("密码不可为空！");
                continue;
            }

            if (password.Length < 6 || password.Length > 20)
            {
                Console.WriteLine("密码长度必须为6-20个字符！");
                continue;
            }
            bool hasUpper = Regex.IsMatch(password, @"[A-Z]");
            bool hasLower = Regex.IsMatch(password, @"[a-z]");
            bool hasNumber = Regex.IsMatch(password, @"[0-9]");

            if (!hasUpper || !hasLower || !hasNumber)
            {
                Console.WriteLine("密码必须包含至少1个大写字母、1个小写字母和1个数字！");
                continue;
            }

            break;
        }

        while (true)
        {
            Console.Write("请确认密码：");
            string confirmPwd = ReadPassword();

            if (confirmPwd != password)
            {
                Console.WriteLine("两次输入的密码不一致，请重新输入！");
                continue;
            }

            break;
        }

        bool success = Register(username, password);
        if (success)
        {
            Console.WriteLine("\n注册成功！");
        }
        else
        {
            Console.WriteLine("\n注册失败，请稍后重试！");
        }
        Pause();
    }

    public void UserLogin()
    {
        Console.Clear();
        Console.WriteLine("===== 用户登录 =====");
        Console.Write("请输入用户名：");
        string username = Console.ReadLine()?.Trim();
        if (string.IsNullOrEmpty(username))
        {
            Console.WriteLine("用户名不可为空！");
            Pause();
            return;
        }

        Console.Write("请输入密码：");
        string password = ReadPassword();

        if (string.IsNullOrEmpty(password))
        {
            Console.WriteLine("密码不可为空！");
            Pause();
            return;
        }

        if (!_users.Exists(u => u.Username == username))
        {
            Console.WriteLine("登录失败：用户名不存在！");
        }
        else if (!Login(username, password))
        {
            Console.WriteLine("登录失败：密码错误！");
        }
        else
        {
            Console.WriteLine($"\n登录成功！欢迎回来，{username}！");
            Console.WriteLine("进入系统首页...");
        }

        Pause();
    }

    private static string ReadPassword()
    {
        string password = "";
        ConsoleKeyInfo key;

        do
        {
            key = Console.ReadKey(true);

            if (key.Key == ConsoleKey.Backspace && password.Length > 0)
            {
                password = password.Substring(0, password.Length - 1);
                Console.Write("\b \b");
            }
            else if (key.Key != ConsoleKey.Enter)
            {
                password += key.KeyChar;
                Console.Write("*");
            }
        } while (key.Key != ConsoleKey.Enter);

        Console.WriteLine();
        return password;
    }

    private static void Pause()
    {
        Console.WriteLine("\n按任意键继续...");
        Console.ReadKey();
    }
}